package com.example.selfservicestation.mob

import com.example.selfservicestation.util.Logger
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import java.util.*

class ScanIdentityReceiver(
    private val listener: (eve: String) -> Unit
) {

    private var eventBusRegistered = false

    private val uuid = UUID.randomUUID().toString()

    companion object {

        private val uuids = ArrayList<Any>()

    }

    fun start() {
        if (!eventBusRegistered) {
            EventBus.getDefault().register(this)
            eventBusRegistered = true
        }
        val count = uuids.count { it == uuid }
        if (count > 0) {
            val itr = uuids.iterator()
            while (itr.hasNext()) {
                if (itr.next() == uuid) {
                    itr.remove()
                }
            }
        }
        uuids.add(uuid)
    }

    @Subscribe
    fun onIdentityEvent(eve: String) {
        // 只有最上层的 ScannerManager 才能监听到消息
        if (uuids.isEmpty()) {
            Logger.i("SCAN_REC", "接收器列表为空")
            return
        }
        Logger.i("SCAN_REC", "当前接收器：${uuid} :: ${uuids[uuids.size - 1]}")
        if (uuids.size > 0 && uuids[uuids.size - 1] == uuid) {
            listener(eve)
        }
    }

    fun stop() {
        if (eventBusRegistered) {
            EventBus.getDefault().unregister(this)
            eventBusRegistered = false
        }
        uuids.remove(uuid)
    }

}